package com.github.defense.plugin.base.subscriber;

import com.github.defense.common.dto.Plugin;
import com.github.defense.common.enums.DataEventTypeEnum;
import com.github.defense.sync.data.api.PluginSubscriber;
import com.github.defense.sync.data.api.cache.CacheData;
import com.sun.istack.internal.NotNull;
import org.springframework.lang.NonNull;

import java.util.Optional;

/**
 * 默认插件处理器
 *
 * @Author: lettger
 * @Date: 2022/1/13 10:30
 */
public class DefaultPluginSubscriber implements PluginSubscriber {

    @Override
    public void onSubscribe(Plugin plugin) {
        defaultHandler(plugin, DataEventTypeEnum.UPDATE);
    }

    @Override
    public void unSubscribe(Plugin plugin) {
        defaultHandler(plugin, DataEventTypeEnum.DELETE);
    }

    @Override
    public void refreshAll() {
        CacheData.getInstance().cleanPlugin();
    }


    private <T> void defaultHandler(final T classData, final DataEventTypeEnum dataType) {
        if (dataType == DataEventTypeEnum.UPDATE) {
            Optional.ofNullable(classData).ifPresent(data -> updateCacheData(classData));
        } else if (dataType == DataEventTypeEnum.DELETE) {
            Optional.ofNullable(classData).ifPresent(data -> removeCacheData(classData));
        }
    }

    /**
     * update cache data.
     */
    private <T> void updateCacheData(@NonNull final T data) {
        if (data instanceof Plugin) {
            Plugin plugin = (Plugin) data;
            CacheData.getInstance().cachePlugin(plugin);
        }
    }

    /**
     * remove cache data
     *
     * @param data
     * @param <T>
     */
    private <T> void removeCacheData(@NotNull final T data) {
        if (data instanceof Plugin) {
            Plugin plugin = (Plugin) data;
            CacheData.getInstance().removePlugin(plugin);
        }
    }

}
